package cn.com.fssg.platform.base.handler.impl.cl.jiesuan;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @className: Cldyq
 * @description: TODO 代用券
 * @author: xzm
 * @date: 2025/10/6
 **/
@Component
public class Cldemo implements InterfaceHandler {


    //private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String countSql = "SELECT count(1) as total, count(cjr_num) as has_cjr_card FROM cl_apply_xunlian";
        Map<String, Object> paraMap = new HashMap<String, Object>();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> countMap;
        try{
            countMap = jdbcTemplate.queryForMap(countSql, paraMap);
        } catch (Exception e) {
            return "获取持证人数异常：" + e.getMessage();
        }
        int currentYear = Integer.parseInt(yearFormat.format(new Date()));
        String start = currentYear + "-01-01";
        String end = currentYear + "-12-31";
        String querySql = "SELECT " +
                "    TO_CHAR(apply_time, 'YYYY-MM') AS month," +
                "    COUNT(*) AS total_count," +
                "    COUNT(cjr_num) AS has_cjr_card," +
                "    COUNT(*) - COUNT(cjr_num) AS has_no_card" +
                " FROM cl_apply_xunlian " +
                " WHERE apply_time >= '%s' AND apply_time <= '%s' " +
                " GROUP BY TO_CHAR(apply_time, 'YYYY-MM') " +
                " ORDER BY month";

        querySql = String.format(querySql, start, end);
        List<Map<String, Object>> list;
        try {
            list = jdbcTemplate.queryForList(querySql, paraMap);

        } catch (Exception e) {
            return "获取全年持证人数异常：" + e.getMessage();
        }
        resultMap.put("numCount", countMap);
        resultMap.put("monthCount", list);
        return resultMap;
    }
}